var chart = null; // 定义全局变量
//获取所有网关信息
var gatewayID=new Array()
var index
var visited = new Array()
function getGateways() {
    index = 0
    $.ajax({
        type: "get",
        url: "http://iot.wduozhi.xyz/api/gateway",
        dataType: "json",
        success: function (data) {
            console.log(data);
            if(data.status === 'error'){
                alert("请先登录！！")
                window.location.href = "../index.html"
            }
            data.data.forEach(element =>{
                var li = '<li class="dropdown">' +
                    '<a class="dropdown-toggle" data-toggle="dropdown" href="#">' +
                    '<h4>'+ element.description + '<span class="caret"></span> </h4>' +
                    '</a>' + '</li>';
                $('#test').append(li);

                var option = '<option value =' + element.id + '>' + element.description  + '</option>';
                $('#gate_id').append(option);
                $('#gate_id2').append(option);
                gatewayID[index++] = element.id;
                visited[index] = 0;
                localStorage.setItem('g' + element.id, element.description)
            })
        },
        error: function () {
            console.log("error!");
        }
    })
}

//监听网关列表事件(获取网关信息+该网关下传感器信息）
var sensorID  = new Array()
var gatewayTempID = -1
$("#test").on('click', 'li',function (){
    var loc = $(this).index()
    var temp = $(this)
    $(this).children('ul').remove();
    if($(this).parent()[0] === $("#test")[0]){//判断是否为直接子元素
        index = 0
        gatewayTempID = gatewayID[loc]
        if(visited[gatewayTempID] === 0){
            visited[gatewayTempID] = 1
            $.ajax({
                type: "get",
                url:  "http://iot.wduozhi.xyz/api/gateway/sensors/" + gatewayID[loc],
                dataType: "json",
                success:function (data) {
                    console.log(data);
                    var ul = '<ul class="dropdowm-meun">'
                    data.data.forEach(element =>{
                        ul += ' <li><a href="#">' + element.description + '</a></li>'
                        sensorID[index++] = element.id;
                        localStorage.setItem('s' + element.id, element.description)
                    })
                    ul += '</ul>'
                    $(temp).append(ul)
                },
                error:function () {
                    console.log("error!");
                }
            });

            $.ajax({
                type:"get",
                url: "http://iot.wduozhi.xyz/api/gateway/" + gatewayID[loc],
                dataType:"json",
                success:function (data) {
                    console.log(data)
                    $("#gatewayID").val(data.data.id)
                    $("#descriptionGate2").val(data.data.description)
                    $("#locationGate2").val(data.data.location)
                    $("#ipAddr2").val(data.data.ip)
                    $("#port2").val(data.data.port)

                    $("#gateID").text(data.data.description)
                    // $("#gatewayDes").text("简 介： " + data.data.description)
                    $("#gatewayLoc").text("地 点： " + data.data.location)
                    $("#gatewayIP").text("IP: " + data.data.ip)
                    $("#gatewayPort").text("端 口： " + data.data.port)
                },
                error:function () {
                    console.log("error!");
                }
            })
        }else{
            visited[gatewayTempID] = 0
        }

    }
    return false;
})

//删除网关
function deleteGeteway() {
    if(gatewayTempID === -1){
        alert("请先点击选择您要删除的网关")
    }else{
        var a = window.confirm("删除网关会把网关下的传感器同时删除，确定删除" + localStorage.getItem('g' + gatewayTempID) + " ？")
        if(a === true){
            $.ajax({
                type: "delete",
                url: "http://iot.wduozhi.xyz/api/gateway/" + gatewayTempID,
                dataType: "josn",
                success:function (data) {
                    console.log(data)
                },
                error:function (data) {
                    console.log("error!")
                }
            })
            alert("删除成功！")
            window.location.reload();
        }
    }
}

//下载网关日志
function downLog() {
    if(gatewayTempID === -1){
        alert("请先点击选择您要下载网关的日志")
    }else{
        // alert("确定下载传感器" + downID + "的日志信息 ？")
        var a = window.confirm("确定下载" + localStorage.getItem('g' + gatewayTempID) + "的日志信息 ？")
        if(a === true){
            var url = "http://iot.wduozhi.xyz/api/file/gateway?id=" + gatewayTempID
            window.location.href = url
        }
    }
}

//修改网关信息
function modifyGate() {

    if(gatewayTempID === -1){
        alert("请先点击选择您要修改的网关")
    }else {
        $.ajax({
                type: "put",
                url: "http://iot.wduozhi.xyz/api/gateway",
                data: $('#ModifyForm2').serialize(),
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    if (data.status === "success") {
                        alert("修改网关信息成功");
                        $("#modifyGate").click();      //关闭修改窗口
                        window.location.reload();
                    } else {
                        showMsg("修改信息失败");
                    }
                },
                error: function () {
                    console.log("error!");
                    showMsg("500：修改信息失败")
                }
            }
        )
    }
}

var downID = -1
var sensorType
//获取传感器信息
$("#test").on('click', 'li',function (){
    //获取传感器id
    var loc = $(this).index()
    // console.log($(this));
    // console.log(loc);
    if($(this).parent()[0] != $("#test")[0]){
        downID = sensorID[loc]
        $.ajax({
            type: "get",
            url: "http://iot.wduozhi.xyz/api/sensor/" + sensorID[loc],
            dataType: "json",
            success: function (data) {
                console.log(data);
                $("#desc").text(data.data.description);
                $("#loc").text(data.data.location);
                $("#fac").text(data.data.factory);
                $("#proTime").text(data.data.produce_date);
                $("#insTime").text(data.data.install_time);
                $("#mainTime").text(data.data.maintenance_time);
                var title = {
                    // text:data.data.sensorClassify.name + '-传感器' + downID
                    text:data.data.description
                };
                chart.setTitle(title);
                if(data.data.sensorClassify.id === 1){
                    chart.yAxis[0].setTitle({
                        text: '温度(摄氏度)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 2){
                    chart.yAxis[0].setTitle({
                        text: '湿度(%RH)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 3){
                    chart.yAxis[0].setTitle({
                        text: '浓度(ppm)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 4){
                    chart.yAxis[0].setTitle({
                        text: '霍尔(RH)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 5){
                    chart.yAxis[0].setTitle({
                        text: '坎德拉(cd)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 6){
                    chart.yAxis[0].setTitle({
                        text: '水位(mm)',
                        x: -20,
                        rotation: 90
                    });
                }else if(data.data.sensorClassify.id === 7){
                    chart.yAxis[0].setTitle({
                        text: '浓度(ppm)',
                        x: -20,
                        rotation: 90
                    });
                }
                requestData()
            }
        })
    }
})

// 增加传感器
function addDev() {
    $(".alert").text(" ");
    $.ajax({
            type: "post",
            url: "http://iot.wduozhi.xyz/api/sensor",
            data: $('#addForm').serialize(),
            dataType: "json",
            success: function (data) {

                console.log(data);
                if (data.status === "success") {
                    alert("添加传感器成功");
                    $("#add").click();      //关闭窗口
                    $("#addForm")[0].reset(); //清空表单
                    window.location.reload();
                } else {
                    showMsg("添加失败");
                }
            },
            error: function () {
                console.log("error!");
                showMsg("500：添加失败")
            }
        }
    )
}

//删除传感器
function deleteSensors() {
    if(downID === -1){
        alert("请先点击选择您要删除的传感器")
    }else{
        var a = window.confirm("确定删除" + localStorage.getItem('s' + downID) + " ？")
        if(a === true){
            $.ajax({
                type: "delete",
                url: "http://iot.wduozhi.xyz/api/sensor/" + downID,
                dataType: "josn",
                success:function (data) {
                    console.log(data)
                },
                error:function () {
                    console.log("error!")
                }
            })
            alert("删除成功！")
            window.location.reload();
        }
    }
}

//修改传感器信息

$('#devModify').click(function (){
    if(downID === -1){
        alert("请先点击选择您要更新信息的传感器")
    }else{
        $.ajax({
            type: "get",
            url: "http://iot.wduozhi.xyz/api/sensor/" + downID,
            dataType: "json",
            success: function (data) {
                console.log(data);
                $("#id2").val(downID);
                $("#description2").val(data.data.description);
                $("#location2").val(data.data.location);
                $("#factory2").val(data.data.factory);
                $("#produce_date2").val(data.data.produce_date);
                $("#install_time2").val(data.data.install_time);
                $("#maintenance_time2").val(data.data.maintenance_time);
                $("#gate_id2 option[value = " + gatewayTempID + "]").attr("selected", "selected");
                $("#classify_id2 option[value = " + data.data.sensorClassify.id + "]").attr("selected", "selected");
            }
        })
    }
})

function modifyMsg() {
    $(".alert").text(" ");
    $.ajax({
            type: "put",
            url: "http://iot.wduozhi.xyz/api/sensor",
            data: $('#ModifyForm').serialize(),
            dataType: "json",
            success: function (data) {
                console.log(data);
                if (data.status === "success") {
                    alert("修改传感器信息成功");
                    $("#modify").click();      //关闭修改窗口
                    window.location.reload();
                } else {
                    showMsg("修改信息失败");
                }
            },
            error: function () {
                console.log("error!");
                showMsg("500：修改信息失败")
            }
        }
    )
}

//下载传感器信息
function downloadeLog() {
    if(downID === -1){
        alert("请先点击选择您要下载传感器的日志")
    }else{
        // alert("确定下载传感器" + downID + "的日志信息 ？")
        var a = window.confirm("确定下载" + localStorage.getItem('s' + downID) + "的日志信息 ？")
        if(a === true){
            var url = "http://iot.wduozhi.xyz/api/file/sensor?id=" + downID
            window.location.href = url
        }
    }
}


function showMsg(msg) {
    $(".alert").text( msg);
}


$(document).ready(function() {
    chart = Highcharts.chart('container', {
        chart: {
            type: 'spline',
            events: {
                load: requestData // 图表加载完毕后执行的回调函数
            }
        },
        title: {
            text: ''
        },
        xAxis: {
            //表示为时间，注意大小写
            type: 'datetime',
            //间距，时间戳，以下表示间距为1天，如果想表示间距为1周，就这么写
            //7*24*3600*1000
            tickInterval:  24 * 3600 * 1000,
            //格式化时间，day,week....
            dateTimeLabelFormats: {
                day: '%Y-%m-%d'
            }
        },
        yAxis: {

            title: {
                text: 'Value',
            }
        },
        series: [{
            name: '数据',
            data: []
        }]
    });
});

var itemp = 0
var chufa
function requestData() {
    // console.log(downID);
    if(itemp !== 0){
        clearTimeout(chufa)
        itemp = 0
    }
    if(downID !== -1){
        itemp = downID
        $.ajax({
            type:"get",
            url: 'http://iot.wduozhi.xyz/api/sensor/data/' + downID,
            dataType: "json",
            success: function(data) {
                var series = chart.series[0],
                    shift = series.data.length > 20; // 当数据点数量超过 20 个，则指定删除第一个点
                // 新增点操作
                //具体的参数详见：https://api.hcharts.cn/highcharts#Series.addPoint
                data.data.forEach(element =>{
                    var point = new Array(element.time, element.data)
                    chart.series[0].addPoint(point, true, shift);
                })
                //5秒后继续调用本函数
                itemp++
               chufa = setTimeout(requestData, 5000);

            },
            cache: false
        });
    }
}

